<template>
	<div>
		<el-form :inline="true">
			<el-form-item>
				<el-input
					v-model="search_form.name"
					placeholder="角色名称"
					clearable
				>
				</el-input>
			</el-form-item>

			<el-form-item>
				<el-button @click="get_role_list">搜索</el-button>
        <el-button @click="handle_reset">重置</el-button>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="dialog_visible = true" v-has="'system:role:add'">新增</el-button>
			</el-form-item>
			
		</el-form>

		<el-table
				:data="role_list"
				tooltip-effect="dark"
				style="width: 100%"
				border
				stripe>

			<el-table-column
					prop="id"
					label="角色ID"
					width="80">
			</el-table-column>
			<el-table-column
					prop="name"
					label="角色名称"
					width="180">
			</el-table-column>
			<el-table-column
					prop="remark"
					label="角色描述">
			</el-table-column>

			<el-table-column
					prop="status"
					label="状态">
				<template slot-scope="scope">
					<el-tag size="small" v-if="scope.row.status === 1" type="success">正常</el-tag>
					<el-tag size="small" v-else-if="scope.row.status === 0" type="danger">禁用</el-tag>
				</template>
			</el-table-column>
			<el-table-column
				prop="created"
				label="创建时间">
			</el-table-column>
			<el-table-column
					label="操作">
				<template slot-scope="scope">
					<el-button type="text" @click="perms_handle(scope.row.id)" v-has="'system:role:perms'">分配权限</el-button>
					<el-divider direction="vertical"></el-divider>

					<el-button type="text" @click="edit_handle(scope.row.id)" v-has="'system:role:edit'">编辑</el-button>
					<el-divider direction="vertical"></el-divider>

					<template>
						<el-popconfirm title="确定删除吗？" @confirm="del_handle(scope.row.id)">
							<el-button type="text" slot="reference" v-has="'system:role:delete'">删除</el-button>
						</el-popconfirm>
					</template>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
				@size-change="handle_size_change"
				@current-change="handle_current_change"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100]"
				:current-page="page_num"
				:page-size="page_size"
				:total="total">
		</el-pagination>

		<!--新增对话框-->
		<el-dialog
				title="提示"
				:visible.sync="dialog_visible"
				width="600px"
				:before-close="handle_close">

			<el-form :model="role_form" :rules="edit_form_rules" ref="role_form">
			<el-form-item label="角色名称" prop="name" label-width="100px">
				<el-input v-model.trim="role_form.name" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="角色编码" prop="code" label-width="100px">
				<el-input v-model.trim="role_form.code" autocomplete="off"></el-input>
			</el-form-item>

			<el-form-item label="角色描述" prop="remark" label-width="100px">
				<el-input v-model.trim="role_form.remark" type="textarea" rows="3"></el-input>
			</el-form-item>

			<el-form-item label="状态"  prop="status" label-width="100px">
				<el-radio-group v-model="role_form.status">
					<el-radio :label="0">禁用</el-radio>
					<el-radio :label="1">正常</el-radio>
				</el-radio-group>
			</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="reset_form('role_form')">取 消</el-button>
				<el-button type="primary" @click="submit_form('role_form')">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 分配权限对话框 -->
		<el-dialog title="分配权限" :visible.sync="perms_dialog_visible" width="600px">
			<el-form :model="role_form">
				<el-tree
						:data="menu_tree_data"
						show-checkbox
						ref="menu_tree"
						:check-strictly="check_strictly"
						node-key="id"
						:default-expand-all="true"
						:props="default_props">
				</el-tree>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="perms_dialog_visible = false">取 消</el-button>
				<el-button type="primary" @click="submit_perms_handle">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import menuApi from '@/api/sys-menu.js'
import roleApi from '@/api/sys-role.js'
	export default {
		name: "Role",
		data() {
			return {
				search_form: {
						name: ''
				},
				total: 0,
				page_size: 10,
				page_num: 1,

				dialog_visible: false,
			role_form: {},

				role_list: [],

				edit_form_rules: {
					name: [
						{required: true, message: '请输入角色名称', trigger: 'blur'}
					],
					code: [
						{required: true, message: '请输入角色编码', trigger: 'blur'}
					],
					status: [
						{required: true, message: '请选择状态', trigger: 'blur'}
					]
				},



				perms_dialog_visible: false,
				default_props: {
					children: 'children',
					label: 'name'
				},
				role_form: {},
				menu_tree_data: [],
				check_strictly: true
			}
		},
		created() {
			this.get_role_list()
			this.load_menu_tree()
		},
		methods: {
			handle_size_change(val) {
				this.page_size = val
				this.get_role_list()
			},
			handle_current_change(val) {
				this.page_num = val
				this.get_role_list()
			},

			reset_form(formName) {
				if (this.$refs[formName]) {
					this.$refs[formName].resetFields();
				}
				this.dialog_visible = false
				this.role_form = {}
			},
			handle_close() {
						this.reset_form('role_form')
				},

			load_menu_tree() {
				menuApi.tree().then(res => {
					this.menu_tree_data = res.data || []
				})
			},

			get_role_list() {
        roleApi.list({
			name: this.search_form.name,
			page_num: this.page_num,
			page_size: this.page_size
		}).then(res => {
		if (res && res.data) {
			this.role_list = res.data.records || []
			this.page_size = res.data.size || this.page_size
			this.page_num = res.data.current || this.page_num
			this.total = res.data.total || 0
		} else {
			this.role_list = []
			this.total = 0
		}
		}).catch(error => {
			console.error('获取角色列表失败:', error)
			this.role_list = []
			this.total = 0
		})
      },
      // 重置搜索条件
      handle_reset() {
        this.search_form = {
          name: ''
        };
        this.get_role_list();
      },

			submit_form(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					const api = this.role_form.id ? roleApi.update : roleApi.add
					api(this.role_form).then(res => {
						this.$message({
						showClose: true,
						message: this.role_form.id ? '更新成功' : '创建成功',
						type: 'success',
						onClose: () => {
							// 代码移到下一行
						}
					});
					this.get_role_list()
					this.dialog_visible = false
				}).catch(error => {
					this.$message.error('操作失败：' + (error.message || '未知错误'));
					console.error('角色操作失败:', error);
				})
				} else {
					return false;
				}
			});
			},
			edit_handle(id) {
				roleApi.detail(id).then(res => {
					this.role_form = res.data
					this.dialog_visible = true
				}).catch(error => {
					this.$message.error('获取角色详情失败：' + (error.message || '未知错误'));
					console.error('获取角色详情失败:', error);
				})
			},
			del_handle(id) {
					if (!id) {
						return;
					}
					roleApi.delete(id).then(() => {
						this.$message({
							showClose: true,
							message: '操作成功',
							type: 'success',
							onClose: () => {
								// 代码移到下一行
							}
						});
						this.get_role_list()
					}).catch(error => {
						this.$message.error('删除失败：' + (error.message || '未知错误'));
						console.error('删除角色失败:', error);
					})
			},

			perms_handle(id) {
				this.perms_dialog_visible = true
				roleApi.detail(id).then(res => {
					if (res && res.data) {
						this.role_form = res.data
						const menuIds = (res.data.sys_menus || []).map(row => row.id)
						// 延迟设置选中项，确保树已渲染
						this.$nextTick(() => {
							this.$refs.menu_tree.setCheckedKeys(menuIds)
						})
					}
				}).catch(error => {
					this.$message.error('获取角色信息失败：' + (error.message || '未知错误'));
					console.error('获取角色信息失败:', error)
				})
			},
		submit_perms_handle() {
				const menuIds = this.$refs.menu_tree.getCheckedKeys()
				roleApi.perm({
					roleId: this.role_form.id,
					menuIds: menuIds
				}).then(res => {
					this.$message({
						showClose: true,
						message: '操作成功',
						type: 'success',
						onClose: () => {
							// 代码移到下一行
						}
					});
					this.get_role_list()
					this.perms_dialog_visible = false
				}).catch(error => {
					this.$message.error('分配权限失败：' + (error.message || '未知错误'));
					console.error('分配权限失败:', error);
				})
			}
		}
	}
</script>

<style scoped>
	.el-pagination {
		float: right;
		margin-top: 22px;
	}
</style>